package com.mj.mirror.activity;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

import com.dyk.hfsdk.dao.util.DevListener;
import com.dyk.hfsdk.ui.Access;
import com.mj.mirror.R;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 魔镜
 * @author zhaominglei
 * @date 2015-2-3
 * 
 */
public class MainActivity extends Activity implements OnClickListener,SurfaceHolder.Callback,DevListener {
	@SuppressWarnings("unused")
	private static final String TAG = MainActivity.class.getSimpleName();
	private boolean isExit = false;
	private TimerTask timerTask;
	private FrameLayout mirrorLayout;
	private TextView adTxt;
	private ImageView mirrorExit; // 退出
	private SurfaceView mirrorPreview;
	private SurfaceHolder surfaceHolder;
	private Camera camera; //摄像头
	private Camera.Parameters parameters;
	private Handler handler = new Handler(); //启动2秒后隐藏标题框
	private Access access;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		mirrorLayout = (FrameLayout)findViewById(R.id.mirror_framelayout);
		adTxt = (TextView)findViewById(R.id.mirror_ad_title);
		mirrorExit = (ImageView)findViewById(R.id.mirror_exit);
		mirrorPreview = (SurfaceView)findViewById(R.id.mirror_preview);
		mirrorExit.setOnClickListener(this);
		
		surfaceHolder = mirrorPreview.getHolder();  
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
		surfaceHolder.setKeepScreenOn(true);
		surfaceHolder.addCallback(this);  
		mirrorPreview.setFocusable(true);
		mirrorPreview.setOnClickListener(this);
		mirrorLayout.setOnClickListener(this);
		adTxt.setOnClickListener(this);
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
//				mirrorLayout.setVisibility(View.GONE);
			}
		}, 3*1000);
		
		access = Access.getInstance();
		// 初始化带player_id
		access.init(MainActivity.this, "a6f7960055ed613a4Ot0X3CS9wJVDJd5QFXp9TRBqsKuUpcvH77XFUzhSAYp0X4ONA", "木蚂蚁");
		// 设置初始积分                                                              
		access.setdefaultSCORE(this, 100);
		// 设置获取积分的监听
		access.setAppListener(this, this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mirror_exit:
			finish();
			break;
		
		case R.id.mirror_preview:
//			int visibility = mirrorLayout.getVisibility();
//			mirrorLayout.setVisibility((visibility == View.VISIBLE) ? View.GONE : View.VISIBLE);
			break;
			
		case R.id.mirror_framelayout:
			access.openWALL(MainActivity.this);
			break;
		case R.id.mirror_ad_title:
			access.openWALL(MainActivity.this);
			break;
			
		default:
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,	int height) {
		//自动对焦
		camera.autoFocus(new AutoFocusCallback() {
			@Override
			public void onAutoFocus(boolean success, Camera camera) {
				if (success) {
					initCamera();//相机的参数初始化
				}
			}
		}); 
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (camera == null) {
			camera = Camera.open(findCamera("front"));
			try {
				camera.setPreviewDisplay(surfaceHolder);
				initCamera();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		camera.release();
		camera = null;
	}
	
	/**
	 * 调用原生摄像头
	 */
	@SuppressWarnings("unused")
	private void callCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
		intent.putExtra("camerasensortype", 2); // 调用前置摄像头  
		intent.putExtra("autofocus", true); // 自动对焦  
		intent.putExtra("fullScreen", true); // 全屏  
		intent.putExtra("showActionIcons", false);  
		startActivityForResult(intent, 1); 
	}
	
	@TargetApi(9)
	private int findCamera(String position) {
		int cameraCount = 0;
		Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
		cameraCount = Camera.getNumberOfCameras(); // get cameras number

		for (int cameraIndex = 0; cameraIndex < cameraCount; cameraIndex++) {
			Camera.getCameraInfo(cameraIndex, cameraInfo); // get cameraInfo
			//代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
			if (position != null && position.equals("front")) {
				if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
					return cameraIndex;
				}
			} else {
				if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
					return cameraIndex;
				}
			}
		}
		return -1;
	}
	
	private void initCamera() {
		parameters = camera.getParameters();
		parameters.setPictureFormat(PixelFormat.JPEG);
//		parameters.setPictureSize(mirrorPreview.getWidth(), mirrorPreview.getHeight()); //部分定制手机，无法正常识别该方法。
//		parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); //打开闪光灯
		setDispaly(parameters, camera);
		camera.setParameters(parameters);
		camera.startPreview();
		camera.cancelAutoFocus();//如果要实现连续的自动对焦，这一句必须加上
	}

	//控制图像的正确显示方向
	private void setDispaly(Camera.Parameters parameters, Camera camera) {
		if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
			setDisplayOrientation(camera, 90);
		} else {
			parameters.setRotation(90);
		}
	}

	//实现图像的正确显示
	private void setDisplayOrientation(Camera camera, int i) {
		Method downPolymorphic;
		try {
			downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
			if (downPolymorphic != null) {
				downPolymorphic.invoke(camera, new Object[] { i });
			}
		} catch (Exception e) {
			Toast.makeText(MainActivity.this, R.string.mirror_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onDevSucceed(int eggs) {
		System.out.println("积分获取成功:" + eggs);
	}

	@Override
	public void onDevFailed(String message) {
		System.out.println("积分获取失败:" + message);
	}

	@Override
	public void onClose(Context context) {
		((Activity) context).finish();
	}
}
